package com.example.demo.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    //    @Bean
//    public CacheManager cacheManager() {
//        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
//        cacheManager.setCaffeine(caffeineConfig());
//        return cacheManager;
//    }
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager manager = new CaffeineCacheManager();
        // 包装原始Cache为TtlCache
        return new CacheManager() {
            @Override
            public Cache getCache(String name) {
                Cache originalCache = manager.getCache(name);
                return new TtlCache(originalCache, 30, TimeUnit.MINUTES); // 默认30分钟
            }

            @Override
            public Collection<String> getCacheNames() {
                return manager.getCacheNames();
            }
        };
    }

    private Caffeine<Object, Object> caffeineConfig() {
        return Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .maximumSize(100);
    }
}    